/*
 * Copyright (C) 2010 Imavis Srl
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.imavis.avimuxer;

import com.imavis.video.parse.VideoInfo;
import com.imavis.video.parse.VideoParser;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 *
 * @author Aldo Brucale
 */
final class MasterMuxer implements Muxer {
    private final AviMuxer aviMuxer;
    private final boolean dropInitialNKF;
    private final VideoParser parser;
    private final ResolutionPolicy resolution;
    private boolean keyFrameFound;
    private final FramerateAverager averager;

    MasterMuxer(int rate, int scale, final ResolutionPolicy resolution,
            FourCC fourCC, File file, boolean avgRate, boolean dropInitialNKF,
            VideoParser parser)
            throws IOException {
        this(new AviMuxerImpl(rate, scale, resolution.getWidth(),
                resolution.getHeight(), fourCC, file),
                resolution, avgRate, dropInitialNKF, parser);
    }

    MasterMuxer(final AviMuxer aviMuxer, final ResolutionPolicy resolution,
            boolean avgRate, boolean dropInitialNKF, VideoParser parser)
            throws IOException {
        this.aviMuxer = aviMuxer;
        this.resolution = resolution;
        this.averager = avgRate ? new FramerateAverager() : null;
        this.dropInitialNKF = dropInitialNKF;
        this.keyFrameFound = false;
        this.parser = parser;
        aviMuxer.open();
    }

    @Override
    public long length() {
        return aviMuxer.length();
    }

    @Override
    public void close() throws IOException {
        if (averager != null) {
            aviMuxer.setFramerate(averager.getRate(), 1);
        }
        aviMuxer.close();
    }

    @Override
    public void write(byte[] data, Date timestamp) throws IOException {
        final VideoInfo vi = parser.parse(data);
        final Dimension parsedRes = vi.getResolution();
        if ((parsedRes != null) && (resolution == ResolutionPolicy.parsed())) {
            aviMuxer.setResolution(parsedRes.width, parsedRes.height);
        }
        keyFrameFound |= vi.isKeyFrame();
        if (averager != null) {
            averager.update(timestamp);
        }
        if (!dropInitialNKF || keyFrameFound) {
            aviMuxer.write(data, timestamp, vi.isKeyFrame());
        }
    }
}
